import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Table, Button, Popconfirm, Select, InputNumber } from 'antd';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ protocol, loading }) => ({
  protocol,
  loading: loading.models.protocol,
  modalData: protocol.modalData,
}))
@Form.create()
class TableForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: props.detList || [],
      listIndex: 0,
      selectPdList: {},
      isDisable: false,
      sumPrice: 0,
    };
  }

  componentDidMount() {
    const { productList, detList, dispatch, onRef } = this.props;
    if (!detList.length) {
      this.addList();
    } else {
      const newData = detList.map((item, i) => ({ ...item, key: i }));
      newData.forEach(value => {
        const temp = value;
        temp.pdId = [];
        temp.detList.forEach(pdNameitem => {
          const ptemp = pdNameitem;
          if (productList.some(pitem => pitem.pdId === ptemp.pdId)) {
            temp.pdId.push(ptemp.pdId);
            ptemp.isId = true;
          } else {
            temp.pdId.push(ptemp.pdName);
            ptemp.isId = false;
          }
        });
      });
      newData.forEach(items => {
        const temp = items;
        temp.fee = temp.price;
      });
      const sumPrice = newData.reduce((total, currentValue) => total + currentValue.fee || 0, 0);
      this.setState({ data: newData, isDisable: newData.length === productList.length, sumPrice });
      dispatch({
        type: 'protocol/updateModelData',
        payload: { modalData: newData },
      });
    }
    onRef(this);
  }

  //  重置产品选择
  reSetPd = () => {
    const { form } = this.props;
    const { data } = this.state;
    if (data.length) {
      data.forEach((item, index) => {
        form.resetFields([`detList[${index}${item.key}]['pdId']`]);
      });
    }
  };

  // 添加数据
  addList = () => {
    const { productList } = this.props;
    const { data, listIndex } = this.state;
    const newData = data.map(item => ({ ...item }));
    newData.push({
      key: `pdId_${listIndex}`,
      pdId: undefined,
      fee: undefined,
    });
    this.state.listIndex += 1;
    this.setState({ data: newData });
    if (productList && productList.length && productList.length === newData.length) {
      this.state.isDisable = true;
    }
  };

  // 删除数据
  delList = key => {
    const { data } = this.state;
    const { productList } = this.props;
    const newData = data.filter(item => item.key !== key);
    const priceList = [];
    newData.forEach(items => {
      priceList.push(items.fee || 0);
    });
    const sumPrice = priceList.reduce((total, currentValue) => total + currentValue, 0);

    this.setState({ data: newData, sumPrice });
    const { selectPdList } = this.state;
    selectPdList[key] = '';
    const curSleArr = [];
    Object.keys(selectPdList).forEach(k => {
      curSleArr.push(selectPdList[k]);
    });
    const showArr = [];
    if (productList) {
      productList.forEach(item => {
        if (curSleArr.indexOf(item.pdId) === -1) {
          showArr.push(item);
        }
      });
    }

    if (productList && productList.length && productList.length > newData.length) {
      this.setState({ isDisable: false });
    }
    this.setState({ selectPdList });
  };

  // 更改数据
  changeData = (value, key, target) => {
    const { productList } = this.props;
    if (String(target) === 'pdId') {
      const { data } = this.state;

      data.forEach(items => {
        const temp = items;
        if (temp.key === key) {
          temp.pdId = value;
        }
      });

      const { selectPdList } = this.state;
      selectPdList[key] = value;
      const curSleArr = [];
      Object.keys(selectPdList).forEach(k => {
        curSleArr.push(selectPdList[k]);
      });

      const showArr = [];
      productList.forEach(item => {
        if (curSleArr.indexOf(item.pdId) === -1) {
          showArr.push(item);
        }
      });
      this.setState({ selectPdList });
    }
    const { data } = this.state;
    if (String(target) === 'fee') {
      // 计算总价
      const newData = data;
      newData.forEach(item => {
        const temp = item;
        if (String(temp.key) === String(key)) {
          temp[target] = value;
        }
      });
      const priceList = [];
      newData.forEach(items => {
        priceList.push(items.fee || 0);
      });
      const sumPrice = priceList.reduce((total, currentValue) => total + currentValue, 0);

      if (typeof sumPrice === 'string') {
        this.setState({ sumPrice: parseInt(sumPrice, 10) });
      } else {
        this.setState({ sumPrice });
      }
    }
  };

  //
  render() {
    const {
      productList,
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 14 },
    };
    const { sumPrice, data } = this.state;
    const columns = [
      {
        title: '选择产品',
        dataIndex: 'pdId',
        width: '40%',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record, index) => (
          <FormItem {...formItemLayout} label="&nbsp;" colon={false}>
            {getFieldDecorator(`detList[${index}${record.key}]['pdId']`, {
              rules: [
                {
                  required: true,
                  message: '请选择',
                },
              ],
              initialValue: record.pdId,
            })(
              <Select
                placeholder="请选择"
                style={{ width: 200 }}
                notFoundContent="暂无数据"
                onChange={value => this.changeData(value, record.key, 'pdId')}
                label="&nbsp;"
                colon={false}
                mode="multiple"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {productList &&
                  productList.map(item => (
                    <Option key={item.pdId} value={item.pdId}>
                      {item.pdName}
                    </Option>
                  ))}
              </Select>
            )}
          </FormItem>
        ),
      },
      {
        title: (
          <span>
            价格<span>(总价：{sumPrice === 0 ? 0 : sumPrice.toFixed(2)})</span>
          </span>
        ),
        dataIndex: 'fee',
        align: 'right',
        width: '40%',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record, index) => (
          <FormItem {...formItemLayout} label="&nbsp;" colon={false}>
            {getFieldDecorator(`detList[${index}${record.key}]['fee']`, {
              rules: [
                {
                  required: true,
                  message: '请输入',
                },
              ],
              initialValue: record.fee,
            })(
              <InputNumber
                placeholder="请输入"
                min={0}
                max={9999999.99}
                precision={2}
                style={{ width: 150 }}
                onChange={value => this.changeData(value, record.key, 'fee')}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span style={{ position: 'relative', top: '-12px' }}>
            <Popconfirm title="是否要删除此行？" onConfirm={() => this.delList(record.key)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        ),
      },
    ];

    return (
      <div style={{ width: 500, margin: '0 auto' }}>
        <Table
          style={{ width: '100%' }}
          // loading={loading}
          columns={columns}
          dataSource={data}
          pagination={false}
          notFoundContent="暂无数据"
          rowKey={record => record.pdId || record.key}
          className={styles.rowPadding}
        />
        <Button
          style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
          type="dashed"
          onClick={this.addList}
          icon={<PlusOutlined />}
          // disabled={isDisable}
        >
          新增
        </Button>
      </div>
    );
  }
}

export default TableForm;
